#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import string
import urllib2


class Zabbix:
    # 先定义API要用的基本信息
    def __init__(self):
        self.url = 'http://192.168.100.3/api_jsonrpc.php'
        self.header = {'Content-Type': 'application/json'}
        self.authID = self.login()

    # 登录的json请求，返回认证ID
    def login(self):
        data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": "Admin",  #zabbix的管理员账号
                "password": "zabbix"  #zabbix的管理员密码
                  },
            "id": 0
        })
        request = urllib2.Request(self.url, data)

        for key in self.header:
            request.add_header(key, self.header[key])
        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            print 'Auth Failed', e.code
        else:
            response = json.loads(result.read())
            result.close()
            authID = response['result']
            print 'Auth Success!Auth ID is:::', authID
            return authID

    # 取数据的json请求基本格式，下面都要用到
    def get_data(self, data, param=""):
        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])
        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            if hasattr(e, 'reason'):
                print 'We failed to reach a server.'
                print 'Reason: ', e.reason
            elif hasattr(e, 'code'):
                print 'The server could not fulfill the request.'
                print 'Error code: ', e.code
            return 0
        else:
            response = json.loads(result.read())
            result.close()
            return response

    # 取得所有主机组ID
    def get_hostgroup(self):
        data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "hostgroup.get",
            "params": {
                "output": ["groupid", "name"],
             },
            "auth": self.authID,
            "id": 1
        })
        res = self.get_data(data)['result']
        print "Number Of Hosts: ", len(res)
        for group in res:
            print "Group ID:", group['groupid'], "\tGroupName:", group['name']

    # 取得指定hostgroup的hostid一览
    def get_hostids(self, groupid):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": "hostid",
                "groupids": groupid
            },
            "auth": self.authID,
            "id": 2
        })
        res = self.get_data(data)['result']
        hostids = []
        for i in range(len(res)):
            hostids.append(res[i]['hostid'])
        return hostids

    # 获取所有主机和对应的hostid
    def hostsid_get(self):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {"output": ["hostid", "status", "host"]},
            "auth": self.authID,
            "id": 1})
        res = self.get_data(data)['result']
        hostsid = []
        if (res != 0) and (len(res) != 0):
            for host in res:
                if host['status'] == '1':
                    hostsid.append({host['host']:host['hostid']})
                elif host['status'] == '0':
                    hostsid.append({host['host']:host['hostid']})
                else:
                    pass
        return hostsid

    # 查找一台主机的所有图形和图形id
    def hostgraph_get(self, hostname):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {"selectGraphs": ["graphid", "name"],
                           "filter": {"host": hostname}},
            "auth": self.authID,
            "id": 1})
        res = self.get_data(data)['result']
        # 可以返回完整信息rs,含有hostid
        return res[0]['graphs']

    # # 根据hostid一览取得所有host的数据
    # def get_info(self, hostid, method, info, parm=""):
    #     hostinfos = []
    #     data = json.dumps({
    #         "jsonrpc": "2.0",
    #         "method": method,
    #         "params": {
    #             "output": "extend",
    #             "hostids": hostid,
    #             "search": {
    #                 "key_": parm
    #             },
    #         },
    #         "auth": self.authID,
    #         "id": 2
    #     })
    #     res = self.get_data(data)['result']
    #     hostinfos.append(res[0][info]) if len(res) != 0 else hostinfos.append("0")
    #     return hostinfos

    # def get_item(self, hostid):
    #     data = json.dumps({
    #         "jsonrpc": "2.0",
    #         "method": "item.get",
    #         "params": {
    #             "output": ["itemids", "name", "lastvalue", "key_"],
    #             "hostids": hostid,
    #             "sortfield": "name"
    #         },
    #         "auth": self.authID,
    #         "id": 2
    #     })
    #     res = self.get_data(data)['result']
    #     items = []
    #     for value in res:
    #         if '$' in value['name']:
    #             name0 = value['key_'].split('[')[1].split(']')[0].replace(',', '')
    #             name1 = value['name'].split()
    #             if 'CPU' in name1:
    #                 name1.pop(-2)
    #                 name1.insert(1, name0)
    #             else:
    #                 name1.pop()
    #                 name1.append(name0)
    #             name = ' '.join(name1)
    #             tmpitems = {'itemid': value['itemid'], 'key_': value['key_'], 'name': name,
    #                         'lastvalue': value['lastvalue']}
    #         else:
    #             tmpitems = {'itemid': value['itemid'], 'key_': value['key_'], 'name': value['name'],
    #                         'lastvalue': value['lastvalue']}
    #         items.append(tmpitems)
    #     return items

    def get_item(self, host):
        try:
            data = json.dumps({
                "jsonrpc": "2.0",
                "method": "item.get",
                "params": {
                    "output": ["name", "lastvalue", "key_"],
                    "host": host,
                    "sortfield": "name"
                },
                "auth": self.authID,
                "id": 2
            })
            res = self.get_data(data)['result']
            return res
        except Exception:
            return False

    def get_info(self, host, parm=""):
        try:
            data = json.dumps({
                    "jsonrpc": "2.0",
                    "method": "item.get",
                    "params": {
                        "output": "extend",
                        "host": host,
                        "search": {
                            "key_": parm
                        },
                    },
                    "auth": self.authID,
                    "id": 2
                })
            res = self.get_data(data)['result']
            #hostinfos.append(res[0]['lastvalue']) if len(res) != 0 else hostinfos.append("0")
            return res[0]['lastvalue']
        except Exception:
            return False

    # 获取相应主机名的cpu信息
    def getCpu(self, host):
        res = self.get_info(host, 'system.cpu.util[,idle]')
        if res:
            total = string.atof(res)
            return total
        return 0

    # 获取所有主机的cpu信息
    def get_all_cpu(self):
        cpus = []
        for i in range(1, 16):
            cpus.append(self.getCpu('compute'+bytes(i)))
        return cpus

    # 获取可用内存
    def get_available_memory(self, host):
        res = self.get_info(host, 'vm.memory.size[available]')
        if res:
            data = string.atoi(res)
            return data
        else:
            return False

    # 获取总内存
    def get_total_memory(self, host):
        res = self.get_info(host, 'vm.memory.size[total]')
        if res:
            data = string.atoi(res)
            return data
        else:
            return False

    # 获取内存利用率
    def get_memory_use(self, host):
        available = self.get_available_memory(host)
        total = self.get_total_memory(host)
        if available and total:
            data = 1 - string.atof(available)/string.atof(total)
            return data
        else:
            return 0

    # 获取所有主机内存利用率
    def get_all_memory_use(self):
        res = []
        for i in range(1, 16):
            res.append(self.get_memory_use('compute'+bytes(i)))
        return res

    # 获取相应主机名的所有Incoming Traffic
    def getTrafficIns(self, host):
        try:
            res = self.get_item(host)
            total = 0
            for value in res:
                if value['key_'].startswith('net.if.in'):
                    total += string.atof(value['lastvalue'])
            return total
        except Exception:
            return False

    # 获取相应主机名的所有Outgoing Traffic
    def getTrafficOuts(self, host):
        try:
            res = self.get_item(host)
            total = 0
            for value in res:
                if value['key_'].startswith('net.if.out'):
                    total += string.atof(value['lastvalue'])
            return total
        except Exception:
            return False

    # 获取相应主机名对应网口的网络流量
    def getPortTraffic(self, host, port):
        key_in = 'net.if.in['+port+']'
        key_out = 'net.if.out['+port+']'
        res1 = self.get_info(host, key_in)
        res2 = self.get_info(host, key_out)
        if res1 or res2:
            res = string.atoi(res1)+string.atoi(res2)
            return res
        return 0

    # 获取相应主机名的控制网络流量
    def getControlTraffic(self, host):
        return self.getPortTraffic(host, 'eth1')

    # 获取相应主机名的计算网络流量
    def getComputeTraffic(self, host):
        net4 = self.getPortTraffic(host, 'eth4')
        net5 = self.getPortTraffic(host, 'eth5')
        net6 = self.getPortTraffic(host, 'eth6')
        if net4 or net5:
            net = net4 + net5
            return net
        return 0

    def get_all_traffic(self):
        res = []
        for i in range(1, 16):
            res.append(self.getControlTraffic('compute'+bytes(i)))
        return res








